package com.imut.lagain.interceptor;

import com.imut.lagain.service.IAccessLogService;
import com.imut.lagain.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;

/**
 * 访问日志拦截器
 * 用于记录用户访问日志
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class AccessLogInterceptor implements HandlerInterceptor {
    
    private final IAccessLogService accessLogService;
    private final JwtUtil jwtUtil;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("Authorization");
         String unionId = "";
        if (StringUtils.hasText(token)) {
            unionId = jwtUtil.getUnionIdFromToken(token);
        }
        log.info("User {} is accessing {}", unionId, request.getRequestURI());
        accessLogService.logAccess(
            null, // userId will be set later
            request.getRequestURI(), 
            request.getMethod(), 
            request.getRemoteAddr(), 
            request.getHeader("User-Agent"), 
            0, // statusCode not available yet
            0L, // responseTime not available yet
            "" // errorMessage empty
        );
        return true;
    }
}